﻿using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using Module.Core.LoginSystem.Commons.Framwork;
using Module.Core.LoginSystem.Commons.Utilities;
using Module.Core.LoginSystem.Components.Commands;
using Module.Core.LoginSystem.Components.Modules;
using Module.Core.LoginSystem.Components.Roles;

namespace Web.Cms.Commands
{
    public partial class CommandDefinitions : AdminUserControl
    {
        private CommandInfo _selectedCommand = null;
        private int _selectedParentId = 0;
        protected void Page_Load(object sender, EventArgs e)
        {
            lblUpdateStatus.Text = string.Empty;
            if (!Page.IsPostBack)
            {
                dropCommandKey.DataSource = ModuleController.GetAuthenticatedModules();

                dropCommandKey.DataValueField = "CtrlKey";
                dropCommandKey.DataTextField = "Title";
                dropCommandKey.DataBind();
                dropCommandKey.Items.Insert(0, new ListItem("None", ""));

                MiscUtility.FillIndex(dropPriority, 1, 100, 1);

                grdRolePermisions.DataSource = RoleController.GetRoles(CurrentPortalID);
                grdRolePermisions.DataBind();
            }
        }

        protected void tvCommands_SelectedNodeChanged(object sender, EventArgs e)
        {
            tvCommands.SelectedNode.ExpandAll();
            int _curCommandId = ConvertUtility.ToInt32(tvCommands.SelectedValue);
            _selectedCommand = CommandController.GetCommand(_curCommandId);
            if (_selectedCommand == null) return;
            txtCommandID.Text = _selectedCommand.CommandID.ToString();
            txtCommandTitle.Text = _selectedCommand.Title;
            MiscUtility.SelectItemFromList(dropCommandKey, _selectedCommand.CtrlKey);
            MiscUtility.SelectItemFromList(dropPriority, _selectedCommand.Priority.ToString());
            chkEnable.Checked = _selectedCommand.IsEnable;
            chkVisible.Checked = _selectedCommand.IsVisible;
            chkIsSuperAdmin.Checked = _selectedCommand.IsSuperUser;

            foreach (GridViewRow row in grdRolePermisions.Rows)
            {
                Label lblRoleID = (Label)row.FindControl("lblRoleID");
                RolePermisionInfo _rolePermision =
                    CommandController.GetRolePermision(Convert.ToInt32(lblRoleID.Text), _curCommandId);
                if (_rolePermision != null)
                {
                    if (_rolePermision.Read > 0 || _rolePermision.Write > 0)
                    {
                        ((CheckBox)row.FindControl("chkRole")).Checked = true; // changed True 
                        ((CheckBox)row.FindControl("chkRead")).Checked = _rolePermision.Read > 0;
                        ((CheckBox)row.FindControl("chkWrite")).Checked = _rolePermision.Write > 0;
                    }
                    else
                    {
                        ((CheckBox)row.FindControl("chkRole")).Checked = false;
                        ((CheckBox)row.FindControl("chkRead")).Checked = false;
                        ((CheckBox)row.FindControl("chkWrite")).Checked = false;
                    }
                }
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                _selectedParentId = Convert.ToInt32(dropCommandParent.SelectedValue);
                CommandInfo _command = CommandController.GetCommand(ConvertUtility.ToInt32(txtCommandID.Text));
                _command.CtrlKey = dropCommandKey.SelectedValue;
                _command.IsEnable = chkEnable.Checked;
                _command.IsSuperUser = chkIsSuperAdmin.Checked;
                _command.IsVisible = chkVisible.Checked;
                int _parentId = ConvertUtility.ToInt32(dropCommandParent.SelectedValue);
                if (_command.CommandID == _parentId)
                    return;
                _command.ParentID = _parentId;
                //_command.PortalID = CurrentPortalID;
                _command.Priority = ConvertUtility.ToInt32(dropPriority.SelectedValue);
                _command.Title = txtCommandTitle.Text;
                CommandController.UpdateCommand(_command);
                //RolePermisionController.
                foreach (GridViewRow row in grdRolePermisions.Rows)
                {
                    CheckBox chkRole = (CheckBox)row.FindControl("chkRole");
                    int _roleId = ConvertUtility.ToInt32(((Label)row.FindControl("lblRoleID")).Text);
                    if (chkRole.Checked)
                    {
                        CheckBox chkReadPermision = (CheckBox)row.FindControl("chkRead");
                        CheckBox chkWritePermision = (CheckBox)row.FindControl("chkWrite");
                        CommandController.AddPermisionToRole(_roleId, _command.CommandID, chkReadPermision.Checked, chkWritePermision.Checked);
                    }
                    else
                    {
                        CommandController.RemovePermisionFromRole(_roleId, _command.CommandID);
                    }
                }
                lblUpdateStatus.Text = MiscUtility.MSG_UPDATE_SUCCESS;
            }
            catch (Exception ex)
            {
                lblUpdateStatus.Text = ex.Message;
            }
        }

        protected void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                CommandInfo _command = new CommandInfo();
                _command.CtrlKey = dropCommandKey.SelectedValue;
                _command.IsEnable = chkEnable.Checked;
                _command.IsSuperUser = chkIsSuperAdmin.Checked;
                _command.IsVisible = chkVisible.Checked;
                _command.ParentID = ConvertUtility.ToInt32(dropCommandParent.SelectedValue);
                //_command.PortalID = CurrentPortalID;
                _command.Priority = ConvertUtility.ToInt32(dropPriority.SelectedValue);
                _command.Title = txtCommandTitle.Text;
                _command.CommandID = CommandController.CreateCommand(_command);
                //Set Commnand to Default VietAnswer
                CommandController.AddCommandToPortal(_command.CommandID, CurrentPortalID);
                txtCommandID.Text = _command.CommandID.ToString();
                //RolePermisionController.

                foreach (GridViewRow row in grdRolePermisions.Rows)
                {
                    CheckBox chkRole = (CheckBox)row.FindControl("chkRole");
                    int _roleId = ConvertUtility.ToInt32(((Label)row.FindControl("lblRoleID")).Text);
                    if (chkRole.Checked)
                    {

                        CheckBox chkReadPermision = (CheckBox)row.FindControl("chkRead");
                        CheckBox chkWritePermision = (CheckBox)row.FindControl("chkWrite");
                        CommandController.AddPermisionToRole(_roleId, _command.CommandID, chkReadPermision.Checked, chkWritePermision.Checked);
                    }
                    else
                    {
                        CommandController.RemovePermisionFromRole(_roleId, _command.CommandID);
                    }
                }
                lblUpdateStatus.Text = MiscUtility.MSG_UPDATE_SUCCESS;
            }
            catch (Exception ex)
            {
                lblUpdateStatus.Text = ex.Message;
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                int _commandId = ConvertUtility.ToInt32(txtCommandID.Text);
                CommandController.DeleteCommand(_commandId);
                CommandController.RemoveCommandFromPortal(_commandId, CurrentPortalID);
            }
            catch (Exception ex)
            {
                lblUpdateStatus.Text = ex.Message;
            }
        }
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            string _selectedNodePath = string.Empty;
            if (tvCommands.SelectedNode != null)
            {
                _selectedNodePath = tvCommands.SelectedNode.ValuePath;
            }
            LoadCommandForTreeView();
            CommandController.FillToList(dropCommandParent, CurrentPortalID);
            int _tmp = 0;
            if (_selectedParentId != 0) _tmp = _selectedParentId;
            if (_selectedCommand != null) _tmp = _selectedCommand.ParentID;
            if (_tmp != 0)
                MiscUtility.SelectItemFromList(dropCommandParent, _tmp.ToString());
            if (_selectedNodePath != string.Empty)
            {
                TreeNode _selectedNode = tvCommands.FindNode(_selectedNodePath);
                if (_selectedNode != null)
                {
                    _selectedNode.Selected = true;
                    int _dept = _selectedNode.Depth;
                    for (int i = 0; i < _dept; i++)
                    {
                        _selectedNode.Parent.ExpandAll();
                        _selectedNode = _selectedNode.Parent;
                    }
                }
            }
        }
        private void LoadCommandForTreeView()
        {
            tvCommands.Nodes.Clear();
            List<CommandInfo> _lstRoots = CommandController.GetCommands(CurrentPortalID, 0);
            foreach (CommandInfo _cmd in _lstRoots)
            {
                TreeNode _node = new TreeNode(_cmd.Title, _cmd.CommandID.ToString());
                tvCommands.Nodes.Add(_node);
                LoadForCurCommandItem(_node);
            }
        }
        private void LoadForCurCommandItem(TreeNode _curNode)
        {
            int _curCommandId = ConvertUtility.ToInt32(_curNode.Value);
            List<CommandInfo> _lstChilds = CommandController.GetCommands(CurrentPortalID, _curCommandId);
            foreach (CommandInfo _cmd in _lstChilds)
            {
                TreeNode _node = new TreeNode(_cmd.Title, _cmd.CommandID.ToString());
                _curNode.ChildNodes.Add(_node);
                LoadForCurCommandItem(_node);
            }
        }
    }
}